package com.oem.fragment;

import static com.oem.fragment.contant.URLConstant.GATEWAY_URL;

import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.InputType;
import android.util.Log;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.Toast;
import android.widget.VideoView;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializer;
import com.oem.fragment.config.RetrofitClient;
import com.oem.fragment.contant.DefaultValueConstant;
import com.oem.fragment.model.Result;
import com.oem.fragment.model.file.UploadFileParamsDto;
import com.oem.fragment.service.FileService;
import com.oem.fragment.utils.FileUtils;
import com.oem.fragment.utils.FormUtils;

import java.io.File;
import java.io.IOException;
import java.time.DateTimeException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class UploadHelper {

    private static final String TAG = "UploadHelper";

    public static void showFilePreview(Context context, Uri uri, ImageView image, VideoView video) {
        try {
            String mimeType = context.getContentResolver().getType(uri);
            if (mimeType == null) return;

            if (mimeType.startsWith("image/")) {
                image.setVisibility(ImageView.VISIBLE);
                video.setVisibility(VideoView.GONE);
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), uri);
                image.setImageBitmap(bitmap);
            } else if (mimeType.startsWith("video/")) {
                image.setVisibility(ImageView.GONE);
                video.setVisibility(VideoView.VISIBLE);
                video.setVideoURI(uri);
                video.start();
            } else {
                image.setVisibility(ImageView.VISIBLE);
                image.setImageResource(com.oem.fragment.R.drawable.ic_file_preview);
                video.setVisibility(VideoView.GONE);
            }
        } catch (IOException e) {
            image.setImageResource(com.oem.fragment.R.drawable.ic_file_preview);
        }
    }

    public static void uploadFile(Context context, Uri uri, UploadFileParamsDto dto) {
        try {
            File file = FileUtils.createTempFileFromUri(context, uri);
            String mimeType = FileUtils.getMimeType(file.getPath());

            Gson gson = new GsonBuilder()
                    .registerTypeAdapter(LocalDateTime.class, (JsonSerializer<LocalDateTime>) (src, type, context1) ->
                            new JsonPrimitive(src.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss")))) // 强制保留秒
                    .create();


            RequestBody paramBody = RequestBody.create(MediaType.parse("application/json"),
                    gson.toJson(dto));
            RequestBody fileBody = RequestBody.create(MediaType.parse(mimeType), file);
            MultipartBody.Part part = MultipartBody.Part.createFormData("obj", file.getName(), fileBody);

            FileService service = RetrofitClient.getClient(GATEWAY_URL).create(FileService.class);
            service.uploadFileByGallery(part, paramBody).enqueue(new Callback<Result>() {
                @Override
                public void onResponse(Call<Result> call, Response<Result> response) {
                    if (response.isSuccessful()) {
                        Toast.makeText(context, "上传成功", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(context, "上传失败: " + response.code(), Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onFailure(Call<Result> call, Throwable t) {
                    Toast.makeText(context, "上传失败: " + t.getMessage(), Toast.LENGTH_SHORT).show();
                    Log.e(TAG, "上传失败", t);
                }
            });

        } catch (IOException e) {
            Toast.makeText(context, "处理文件失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            Log.e(TAG, "文件处理失败", e);
        }
    }

    public static UploadFileParamsDto createUploadParams(Map<String, EditText> input) {
        UploadFileParamsDto dto = new UploadFileParamsDto();

        dto.setTags(getText(input, "tags", DefaultValueConstant.DEFAULT_TAGS));
        dto.setCategory(getText(input, "category", DefaultValueConstant.DEFAULT_CATEGORY));
        dto.setDescription(getText(input, "description", DefaultValueConstant.DEFAULT_DESCRIPTION));
        dto.setRemark(getText(input, "remark", DefaultValueConstant.DEFAULT_REMARK));

        dto.setBudget(parseDouble(getText(input, "budget", null), DefaultValueConstant.DEFAULT_BUDGET));
        dto.setStartDate(parseDateTime(getText(input, "startDate", DefaultValueConstant.DEFAULT_START_DATE)));
        dto.setEndDate(parseDateTime(getText(input, "endDate", DefaultValueConstant.DEFAULT_END_DATE)));

        return dto;
    }

    public static void uploadFileFromUrl(Context context, String url, UploadFileParamsDto dto) {
        FileService service = RetrofitClient.getClient(GATEWAY_URL).create(FileService.class);

        RequestBody urlBody = RequestBody.create(MediaType.parse("text/plain"), url);
        Gson gson = new GsonBuilder()
                .registerTypeAdapter(LocalDateTime.class, (JsonSerializer<LocalDateTime>) (src, type, context1) ->
                        new JsonPrimitive(src.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss")))) // 强制保留秒
                .create();

        RequestBody paramBody = RequestBody.create(MediaType.parse("application/json"),
                gson.toJson(dto));

        service.uploadFileByURL(urlBody, paramBody).enqueue(new Callback<Result>() {
            @Override
            public void onResponse(Call<Result> call, Response<Result> response) {
                if (response.isSuccessful()) {
                    Toast.makeText(context, "URL 文件上传成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(context, "上传失败: " + response.code(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<Result> call, Throwable t) {
                Toast.makeText(context, "上传失败: " + t.getMessage(), Toast.LENGTH_SHORT).show();
                Log.e("UploadHelper", "URL 上传失败", t);
            }
        });
    }

    private static String getText(Map<String, EditText> input, String key, String defaultValue) {
        return FormUtils.getTextFromEditText(input.get(key), defaultValue);
    }

    private static Double parseDouble(String val, Double defaultValue) {
        if (val == null || val.isEmpty()) return defaultValue;
        try {
            return Double.parseDouble(val);
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("预算参数格式错误");
        }
    }

    private static LocalDateTime parseDateTime(String val) {
        if (val == null || val.isEmpty()) return null;
        try {
            return LocalDateTime.parse(val);
        } catch (DateTimeException e) {
            throw new IllegalArgumentException("时间格式错误：" + val);
        }
    }


}
